#include "../include/logviewer.h"

using namespace Gtk;
using namespace Glib;


void logViewer::newLine(){
    Mutex::Lock lock(mutex);
    logBuffer->insert(logBuffer->get_iter_at_offset(logBuffer->get_char_count()), "\n");
}

logViewer::logViewer()
{
    Mutex::Lock lock(mutex);
    logBuffer=get_buffer(); //it comes with a free buffer 8)
    endMark=logBuffer->create_mark(logBuffer->end(), false);
//    set_buffer(logBuffer);
    RefPtr<TextTag> tagbold = logBuffer->create_tag("bold");
    tagbold->property_weight() = Pango::WEIGHT_BOLD;
    RefPtr<TextTag> tagred = logBuffer->create_tag("red");
    tagred->property_foreground() = "red";
    RefPtr<TextTag> taggreen = logBuffer->create_tag("green");
    taggreen->property_foreground() = "green";
    RefPtr<TextTag> tagredbold = logBuffer->create_tag("boldred");
    tagredbold->property_foreground() = "red";
    RefPtr<TextTag> taggreenbold = logBuffer->create_tag("boldgreen");
    taggreenbold->property_foreground() = "green";
    taggreenbold->property_weight() = Pango::WEIGHT_BOLD;
    update.connect(sigc::mem_fun(*this, &logViewer::beforeDraw));

    update.connect(sigc::mem_fun(*this, &logViewer::beforeDraw));

}

logViewer::~logViewer()
{
    //dtor
}


void logViewer::logRed(ustring msg, bool bold){
        Mutex::Lock lock(mutex);
        tempBuffer.push_back(make_pair(msg, bold?"boldred":"red"));
        update();
}
void logViewer::logGreen(ustring msg, bool bold){
        Mutex::Lock lock(mutex);
        tempBuffer.push_back(make_pair(msg, bold?"boldgreen":"green"));
        update();
}
void logViewer::log(ustring msg, bool bold){
        Mutex::Lock lock(mutex);
        tempBuffer.push_back(make_pair(msg, bold?"bold":""));
        update();
}

 logViewer& logViewer::operator<<(const char msg[]){
 log(msg);
return *this;

}
logViewer& logViewer::operator<<(ustring& msg){
    log(msg);
    return *this;
}

void logViewer::beforeDraw(){
    Mutex::Lock lock(mutex);
    vector<pair<string, string> >::iterator iter;
    for(iter=tempBuffer.begin(); iter<tempBuffer.end(); iter++){
        if((*iter).second != ""){
            logBuffer->insert_with_tag(endMark->get_iter(), (*iter).first + "\n", (*iter).second );
            cout << (*iter).second;
        }
        else
            logBuffer->insert(endMark->get_iter(), (*iter).first + "\n");
    }
    tempBuffer.clear();
    scroll_to_mark(endMark, 0.2);
}
